package com.knowswift.security.handler.success;

import com.knowswift.common.utils.GetUUIDUtils;
import com.knowswift.common.utils.JwtTokenUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.account.UserVO;
import com.knowswift.security.handler.AbstractLoginSuccessHandler;
import com.knowswift.security.param.VerifyParam;
import com.knowswift.security.token.VerifyCodeAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @company https://www.knowswift.com
 */
@Component
public class UserCodeLoginSuccessHandler extends AbstractLoginSuccessHandler {
    @Resource
    private UserService userService;

    @Override
    public Object preAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        VerifyCodeAuthenticationToken verifyCodeAuthenticationToken = (VerifyCodeAuthenticationToken) authentication;
        VerifyParam verifyParam = verifyCodeAuthenticationToken.getVerifyParam();
        User user = (User) authentication.getPrincipal();

//        WechatResponse wechatResponse = verifyParam.getWechatResponse();
//
//        // 如果手机号码登录的账号 openId 和现在的不一致，则解除已有的绑定
//        if (user.getMiniOpenId() != null && !user.getMiniOpenId().equals(wechatResponse.getMiniOpenId())) {
//            User exist = userService.lambdaQuery().eq(User::getMiniOpenId, wechatResponse.getMiniOpenId()).one();
//            if (exist != null) {
//                exist.setMiniOpenId(null);
//                exist.setSubscribed(false);
//                exist.setWechatUnionId(null);
//                exist.setOfficialOpenId(null);
//                userService.updateById(exist);
//            }
//        }

//        user.setMiniOpenId(wechatResponse.getMiniOpenId());
//        user.setWechatUnionId(wechatResponse.getUnionId());
        // 如果是游客
        if (StringUtils.isBlank(user.getNickname())) {
            user.setNickname("用户" + GetUUIDUtils.getUUIDBits(8));
        }
        user.setAppTokenVersion(user.getAppTokenVersion() + 1);
        userService.saveOrUpdate(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put("tokenVersion", user.getAppTokenVersion());
        String token = JwtTokenUtils.generateToken(claims, user.getId());
        UserVO userVo = WrappedBeanCopier.copyProperties(user, UserVO.class);
        userVo.setToken(token);
        return userVo;
    }
}
